package team.bluepen.order.data.database;

import space.lingu.light.connect.ConnectionPool;
import space.lingu.light.connect.DatasourceConfig;
import space.lingu.light.log.JdkDefaultLogger;
import space.lingu.light.log.LightLogger;
import space.lingu.light.util.StringUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Copied from {@link space.lingu.light.connect.simple.DisposableConnectionPool}
 * @author RollW
 */
public class OrderConnectionPool implements ConnectionPool {
    private LightLogger logger = JdkDefaultLogger.getGlobalLogger();
    private DatasourceConfig mDatasourceConfig;

    public OrderConnectionPool(DatasourceConfig config) {
        mDatasourceConfig = config;
    }

    public OrderConnectionPool() {
    }

    @Override
    public void setDataSourceConfig(DatasourceConfig config) {
        mDatasourceConfig = config;
        String className = config.getUrl().startsWith("jdbc:mysql") ?
                "com.mysql.cj.jdbc.Driver" :
                "org.apache.hive.jdbc.HiveDriver";
        try {
            Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Connection requireConnection() {
        if (mDatasourceConfig == null || mDatasourceConfig.getUrl() == null) {
            throw new IllegalStateException("DataSourceConfig is null or URL is null.");
        }
        if (StringUtil.isEmpty(mDatasourceConfig.getPassword()) ||
                StringUtil.isEmpty(mDatasourceConfig.getUsername()) ) {
            try {
                return DriverManager.getConnection(mDatasourceConfig.getUrl());
            } catch (SQLException e) {
                if (logger != null)
                    logger.error(e);
                throw new RuntimeException(e);
            }
        } else {
            try {
                return DriverManager.getConnection(mDatasourceConfig.getUrl(),
                        mDatasourceConfig.getUsername(), mDatasourceConfig.getPassword());
            } catch (SQLException e) {
                if (logger != null)
                    logger.error(e);
                throw new RuntimeException(e);
            }
        }

    }

    @Override
    public void release(Connection connection) {
        if (connection == null) return;
        try {
            connection.close();
        } catch (SQLException e) {
            if (logger != null)
                logger.error(e);
        }
    }

    @Override
    public void close() {
    }

    @Override
    public void setLogger(LightLogger logger) {
        this.logger = logger;
    }

    @Override
    public LightLogger getLogger() {
        return logger;
    }
}
